package com.mcy.springbatch.service.impl;

import com.mcy.springbatch.service.BatchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.configuration.ListableJobLocator;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.launch.NoSuchJobException;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.batch.operations.JobOperator;

/**
 * @author : Create By mcy
 * @date : 2019/8/26 11:16:19
 */
@Slf4j
@Service
public class BatchServiceImpl implements BatchService {

    @Autowired
    ListableJobLocator jobLocator;

//    @Resource(name = "asyncJobLauncher")
    @Autowired
    private JobLauncher jobLauncher;

    @Autowired
    JobRepository jobRepository;

    @Override
    public JobExecution launch(String jobName, JobParameters jobParameters) throws Exception {
        if (!jobLocator.getJobNames().contains(jobName)) {
            throw new NoSuchJobException(jobName);
        }

        Job job = jobLocator.getJob(jobName);
        JobExecution lastJobExecution = jobRepository.getLastJobExecution(jobName, jobParameters);
        boolean restart = false;
        if (lastJobExecution != null) {
            if (lastJobExecution.getStatus().isUnsuccessful() && lastJobExecution.getStatus() != BatchStatus.ABANDONED) {
                restart = true;
            }
        }
        if (job.getJobParametersIncrementer() != null && !restart) {
            jobParameters = job.getJobParametersIncrementer().getNext(jobParameters);
        }
        JobExecution jobExecution = jobLauncher.run(job, jobParameters);
        return jobExecution;
    }
}
